<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use think\Db;
use think\Request;

class School extends Base
{

    /**
     * 文章分类
     */
    public function xueyuan()
    {
        $page  = request()->param('page', '1');
        $limit = request()->param('limit', 10);
        $keyword = request()->param('keywords', '');
        // 总数
        $where = [];


        if ($keyword){
            $where[]=['title','like','%'.$keyword];
        }
        $total = Db::name("Yuan")->where($where)->count();
        // 搜索条件

        $list = Db::name("Yuan")->where($where)->page($page, $limit)->order("id desc")->select();
        if (!empty($list)){
            foreach ($list as $key=>$val){
                $yuanzhang=Db::name("Admin")->where(['uid'=>$val['yuanzhang']])->value('realname');
                $list[$key]['yuanzhang']=empty($yuanzhang)?'暂未安排':$yuanzhang;
                $list[$key]['create_time']=date("Y-m-d H:i:s",$val['create_time']);
            }
        }
        $data = [
            'total'  => $total,
            'list'   => $list,
            'yuanzhang'=>Db::name("Admin")->where(['user_type'=>2])->order("uid desc")->column('uid,realname')
        ];
        return $this->ok($data);
    }


    //添加学院
    public function save_xueyuan()
    {
        $id=request()->param("id",'0','intval');
        $data=request()->only(['title','yuanzhang']);



        if (!empty($data['yuanzhang'])){
            $has_yuanzhang=Db::name("Yuan")->where(['yuanzhang'=>$data['yuanzhang']])->where("id",'neq',$id)->find();
            if (!empty($has_yuanzhang)){
                return $this->fail('该用户已是'.$has_yuanzhang['title'].'的院长,无法重复担任');
            }
        }
        if (empty($id)){
            if (Db::name("Yuan")->where(['title'=>$data['title']])->find()){
                return $this->fail('该学院已存在');
            }
            $data['create_time']=time();

            $res=Db::name("Yuan")->insert($data);
        }else{
            $res=Db::name("Yuan")->where(['id'=>$id])->update($data);
        }

        if ($res){
            return $this->ok('操作成功');
        }else{
            return $this->fail('操作失败');
        }
    }

    //学院详情
    public function xueyuan_detail()
    {
        $id=request()->param("id",'0','intval');
        $detail=Db::name("Yuan")->where(['id'=>$id])->find();
        return $this->ok($detail);
    }



}
